package com.jugheadzhou.cilent1.task;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.nio.charset.Charset;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;

/**
 * @author jugheadzhou
 * @date 2022-04-10
 */
@Slf4j
@Component
public class LeaderLatchTestTask implements LeaderLatchListener {

    @Value("${spring.application.name}")
    private String appName;
    @Value("${server.port}")
    private String port;
    @Setter
    private boolean isSupervisorLeader = false;

    @Scheduled(cron = "0/5 * * * * ?")
    public void leaderLatchTestTaskWriteToFile() {
        if (isSupervisorLeader) {
            try {
                log.info("{}:{} start write to file", appName, port);
                writeToFile();
            } catch (Exception e) {
                log.error("", e);
            }

        }
    }

    public void writeToFile() throws Exception {
        File file = new File("D:\\Projects\\IdeaProjects\\springboot-demo\\springboot-zookeeper\\springboot-zookeeper-client1\\src\\main\\resources\\LeaderLatchTestTaskOutputFile.txt");
        List<String> list = FileUtils.readLines(file, Charset.defaultCharset());
        int num;
        if (CollectionUtils.isEmpty(list)){
            num = 0;
        }else {
            String s = list.get(list.size() - 1);
            log.info("last line is {}", s);
            String[] arr = s.split("-");
            int lastNum = Integer.parseInt(arr[0]);
            num = lastNum + 1;
        }
        FileUtils.writeLines(file, Collections.singletonList(num + "-" + appName + ":" + port + "-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))), true);
    }

    @Override
    public void isLeader() {
        this.isSupervisorLeader = true;
        log.info("I'm leader of supervisor");
    }

    @Override
    public void notLeader() {
        this.isSupervisorLeader = false;
        log.info("I'm not leader of supervisor, i will be standby");
    }

}
